<?php
/**
 *
 */
namespace app\home\controller\address;

use app\home\controller\Base;
use app\common\model\MemberAddress;

class Handle extends Base
{

	private $params;

	public function __construct(){
		parent::__construct();
		// token验证
		if(false == Base::checkToken()){
			$this->error('token error!');
		}
		// 参数去token
		$params = $this -> request -> post();
		 unset($params['token']);
		$this->params = $params;
	}

	/**添加地址
	 */
	public function add(){
		$params = $this->params;
		$result = $this->validate($params, 'Address.home_add');
		if(true !== $result) {
    	    $this->error($result);
        }
		$model = new MemberAddress;
		$res = $model->isDefault(UID);
		$data['default'] = empty($res)?1:0;
		$data = [
			'uid' => UID,
			'title'=>$params['title'],
			'city' => $params['city'],
			'address' => $params['address'],
			'uname' => $params['uname'],
			'mphone' => $params['mphone'],
			'create_time'=>time()
		];
		if(false===$model->addAddress($data)){
			$this->error($model->getError());
		}else{
			$this->success('添加成功');
		}

	}

	public function edit(){
		$params = $this->params;
        $id = $params['id'];
        unset($params['id']);
		$result = $this->validate($params, 'Address.home_edit');
		if(true !== $result) {
    	    $this->error($result);
        }
		$model = new MemberAddress;
		if($model->saveOneData($params,$id)){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
	}

	/**
	 * 设置默认地址
	 */
	public function set_default(){
		$params = $this->params;
		$id = $params['id'];
		$model = new MemberAddress;
		if(false===$model->setDefault($id,UID)){
			$this->error($model->getError());
		}else{
			$this->success('设置成功');
		}
	}

}